import 'dart:math';

import 'package:app_common_js_collect_demo/shared_webview/ts_mine_home_page.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
import 'package:event_bus/event_bus.dart';

import '../base/javascript_channel.dart';
import '../base/lifecycle_base_page.dart';
import '../test_web_controller_util.dart';

import 'ts_mine_home_page.dart';

class TSWebAddToDiffPage extends LifeCyclePage {
  static bool showRedPadding = true;

  final bool? shouldHideNavBar;
  final String url;

  final WebViewWidget? webViewWidget;
  final WebViewController? webController;
  final void Function(
          WebViewWidget webViewWidget, WebViewController webController)?
      onWebViewCreated;

  final bool? allowsInlineMediaPlayback;
  final Set<PlaybackMediaTypes>? mediaTypesRequiringUserAction;

  const TSWebAddToDiffPage({
    Key? key,
    this.shouldHideNavBar = false,
    required this.url,
    this.webViewWidget,
    this.webController,
    this.onWebViewCreated,
    this.allowsInlineMediaPlayback,
    this.mediaTypesRequiringUserAction,
  }) : super(key: key);

  @override
  _TSWebAddToDiffPageState createState() => _TSWebAddToDiffPageState();
}

class _TSWebAddToDiffPageState
    extends LifeCycleBasePageState<TSWebAddToDiffPage> {
  String? _title;
  late WebViewWidget _webViewWidget;
  late WebViewController _webController;
  bool _showLoading = false;

  BuildContext? _jsContext;
  bool _isFirst = true;

  @override
  void dispose() {
    // EventBusUtil.eventBus.fire(ShareWebControllerShowStateEvent(show: true));
    for (var javaScriptChannelName
        in ShareWebViewController.javaScriptChannelNames ?? []) {
      _webController.removeJavaScriptChannel(javaScriptChannelName);
    }
    ShareWebViewController.javaScriptChannelNames = null;

    super.dispose();
  }

  @override
  void viewDidAppear(AppearBecause appearBecause) {
    super.viewDidAppear(appearBecause);

    setState(() {
      // 使用 setState 是为了触发 Widget build(BuildContext context); 的方法
      _loadRequest();
    });
  }

  @override
  void initState() {
    super.initState();

    if (widget.webViewWidget != null && widget.webController != null) {
      _webViewWidget = widget.webViewWidget!;
      // _webViewWidget = WebViewWidget(controller: widget.webController!);
      _webController = widget.webController!;
      _isFirst = false;
    } else {
      _webController = defaultController;
      _webViewWidget = WebViewWidget(controller: _webController);
      widget.onWebViewCreated?.call(_webViewWidget, _webController);
      _isFirst = true;
    }

    if (ShareWebViewController.javaScriptChannelNames == null ||
        ShareWebViewController.javaScriptChannelNames!.isEmpty) {
      _addJs();
    }

    _loadRequest();

    EventBusUtil.eventBus
        .on<ShareWebControllerShowStateEvent>()
        .listen((event) async {
      bool show = event.show;
      onRefresh();
    });
  }

  _loadRequest() {
    // if (!_isFirst) {
    //   return; // 不更新地址，以此来测试之前的页面能否拿来复用
    // }
    _webController.loadRequest(Uri.parse(widget.url));
  }

  onRefresh() {
    if (mounted) {
      setState(() {
        // _showLoading = true;
        if (ShareWebViewController.webViewWidget != null) {
          _webViewWidget = ShareWebViewController.webViewWidget!;
        }
      });
    }
  }

  WebViewController get defaultController {
    PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: widget.allowsInlineMediaPlayback ?? true,
        mediaTypesRequiringUserAction: widget.mediaTypesRequiringUserAction ??
            const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    return WebViewController.fromPlatformCreationParams(params)
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0xfff1f1f1))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            if (mounted) {
              setState(() {
                _showLoading = true;
              });
            }
          },
          onPageFinished: (String url) {
            // _webViewWidget.getTitle().then((title) {
            //   if (mounted) {
            //   setState(() {
            //     _title =  title;
            //   });
            // }
            // });
            if (mounted) {
              setState(() {
                _showLoading = false;
              });
            }
          },
          onProgress: (int progress) {
            // _progressValue = progress / 100;
            // ToastUtil.showMessage('$progress%');

            if (mounted) setState(() {});
          },
          onWebResourceError: (WebResourceError error) async {
            _webController.getTitle().then((title) {});
            // _onErrorInnerHTML();
            //webview页面加载失败log
          },
        ),
      );
  }

  bool _checkContinue() {
    // if (!mounted) {
    //   debugPrint("Error❌:mounted=$mounted");
    //   return false;
    // }
    if (_jsContext == null) {
      debugPrint("Error❌:_jsContext 不能为空");
      return false;
    }
    return true;
  }

  _addJs() {
    Set<JavascriptChannel> javascriptChannels = {
      /// 跳转到app指定页面_Name
      JavascriptChannel(
        name: "mpCallApp_closeMiniProgram",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.popUntil(_jsContext!, (route) {
            // 在根页面时就禁止再次返回
            if (route.settings.name == "/" || route.settings.name == "/home") {
              return true;
            }
            return false;
          });
        },
      ),
      JavascriptChannel(
        name: "mpCallApp_hideMiniProgram",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.pop(_jsContext!);
        },
      ),
      JavascriptChannel(
        name: "mpCallApp_openAppUserDetail1",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.push(_jsContext!, MaterialPageRoute(
            builder: (context) {
              String userId = "1475332557208702976";
              return TSMineHomeViewController(userId: userId);
            },
          ));
        },
      ),
      JavascriptChannel(
        name: "mpCallApp_openAppUserDetail2",
        onMessageReceived: (JavaScriptMessage message) {
          if (!_checkContinue()) return;
          Navigator.push(_jsContext!, MaterialPageRoute(
            builder: (context) {
              String userId = "234054";
              return TSMineHomeViewController(userId: userId);
            },
          ));
        },
      ),
    };

    for (var channel in javascriptChannels) {
      ShareWebViewController.javaScriptChannelNames ??= [];
      ShareWebViewController.javaScriptChannelNames!
          .add(channel.name ?? "unkonw");

      _webController.addJavaScriptChannel(
        channel.name ?? "unkonw",
        onMessageReceived: channel.onMessageReceived,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    _jsContext = context;

    return Scaffold(
      // resizeToAvoidBottomInset: false,
      // appBar: QuickAppBar(
      //   context,
      //   title: _title,
      //   actions: [
      //     ThemeBGButton(
      //       title: "刷新",
      //       bgColorType: ThemeBGType.blue,
      //       onPressed: () {
      //         onRefresh();
      //       },
      //     ),
      //   ],
      // ),
      body: Column(
        children: [
          _renderWebView(),
        ],
      ),
    );
  }

  _renderWebView() {
    return Expanded(
      // WillPopScope拦截手势返回
      child: Stack(
        fit: StackFit.expand,
        children: [
          Container(
            color: TSWebAddToDiffPage.showRedPadding
                ? ColorHelper.randomColor()
                : Colors.white,
            padding: TSWebAddToDiffPage.showRedPadding
                ? const EdgeInsets.only(
                    left: 10, right: 10, top: 10, bottom: 10)
                : EdgeInsets.zero,
            child: _webViewWidget,
          ),
          if (_showLoading) positionedLoadingView,
        ],
      ),
    );
  }

  Widget get positionedLoadingView {
    return Positioned(
      top: 0,
      bottom: 200,
      left: 0,
      right: 0,
      child: Container(
        // color: Colors.white,
        alignment: Alignment.center,
        child: const SizedBox(
          height: 30,
          width: 30,
          child: CircularProgressIndicator(
            strokeWidth: 3,
            valueColor: AlwaysStoppedAnimation(Color(0xFFE67D4F)),
          ),
        ),
      ),
    );
  }
}

class ColorHelper {
  //随机颜色
  static Color randomColor() {
    return Color.fromARGB(255, Random.secure().nextInt(255),
        Random.secure().nextInt(255), Random.secure().nextInt(255));
  }
}
